<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <!-- 导入按钮 -->
          <el-button type="primary" @click="showImportDialog">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
          <el-button type="primary" @click="handleAdd">添加卡片</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="完整卡号">
            <el-input
              v-model="searchForm.CardNumber"
              placeholder="请输入完整卡号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="商户">
            <el-select
              v-model="searchForm.MerchantId"
              placeholder="请选择商户"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.Status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option label="未绑定" :value="1" />
              <el-option label="已绑定" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="上游平台配置">
            <el-select
              v-model="searchForm.UpstreamPlatformId"
              placeholder="请选择上游平台配置"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in upstreamPlatformOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 商户表格 -->
      <el-table 
        :data="userList" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="Id" label="id" />
        <el-table-column prop="CardNumber" label="卡号" show-overflow-tooltip />
        <el-table-column prop="MerchantId" label="商户id" show-overflow-tooltip />
        <el-table-column prop="Merchant" label="商户名称" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatformId" label="上游平台配置id" show-overflow-tooltip />
        <el-table-column prop="UpstreamPlatform" label="上游平台名称" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamConfigId" label="商户平台配置id" show-overflow-tooltip />
        <el-table-column prop="StatusString" label="状态" show-overflow-tooltip />
        <el-table-column prop="CreatedAtString" label="创建时间" show-overflow-tooltip />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/更新卡片对话框 -->
    <el-dialog
      title="添加卡片"
      v-model="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="CardNumber" prop="CardNumber">
          <el-input v-model="userForm.CardNumber" placeholder="请输入卡号" />
        </el-form-item>
        <el-form-item label="商户" prop="MerchantId">
          <el-select
            v-model="userForm.MerchantId"
            placeholder="请选择商户"
            clearable
          >
            <el-option
              v-for="item in merchantIdOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上游平台配置" prop="UpstreamPlatformId">
          <el-select
            v-model="userForm.UpstreamPlatformId"
            placeholder="请选择上游平台配置"
            clearable
          >
            <el-option
              v-for="item in upstreamPlatformOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      title="导入卡片"
      v-model="importDialogVisible"
      width="600px"
      :before-close="handleImportClose"
    >
      <el-form
        ref="importFormRef"
        :model="importForm"
        :rules="importRules"
        label-width="120px"
      >        
        <el-form-item label="商户" prop="MerchantId">
          <el-select
            v-model="importForm.MerchantId"
            placeholder="请选择商户"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in merchantIdOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="上游平台配置" prop="UpstreamPlatformId">
          <el-select
            v-model="importForm.UpstreamPlatformId"
            placeholder="请选择上游平台配置"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in upstreamPlatformOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadRef"
            action=""
            :show-file-list="true"
            :limit="1"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :auto-upload="false"
            :accept="acceptedFileTypes"
            :file-list="importForm.fileList"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 Excel (.xlsx, .xls) 和 CSV (.csv) 格式，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleImportClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleImportSubmit"
            :loading="importLoading"
            :disabled="!importForm.file"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Download } from '@element-plus/icons-vue'
import { importCardList, importCard, addCard } from '@/api/card'
import { upstreamPlatformList, merchantList } from '@/api/selectList'

// 响应式数据
const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const importDialogVisible = ref(false)
const templateDialogVisible = ref(false)
const userFormRef = ref()
const importFormRef = ref()
const uploadRef = ref()
const merchantIdOptions = ref([])
const upstreamPlatformOptions = ref([])
const importLoading = ref(false)

// 支持的文件类型
const acceptedFileTypes = computed(() => {
  return '.xlsx,.xls,.csv'
})

// 模板预览数据
const templatePreviewData = [
  { cardNumber: 'CARD001' },
  { cardNumber: 'CARD002' }
]

// 搜索表单
const searchForm = reactive({
  MerchantId: null,
  UpstreamPlatformId: null,
  CardNumber: '',
  Status: null
})

// 商户表单
const userForm = reactive({
  CardNumber: '',
  MerchantId: null,
  UpstreamPlatformId: null
})

// 导入表单
const importForm = reactive({
  file: null,
  fileList: [],
  MerchantId: null,
  UpstreamPlatformId: null
})

// 表单验证规则
const userRules = {
  CardNumber: [
    { required: true, message: '请输入卡号', trigger: 'blur' }
  ],
  MerchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  UpstreamPlatformId: [
    { required: true, message: '请选择上游平台配置', trigger: 'change' }
  ]
}

// 导入表单验证规则
const importRules = {
  file: [
    { required: true, message: '请选择导入文件', trigger: 'change' }
  ],
  MerchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  UpstreamPlatformId: [
    { required: true, message: '请选择上游平台配置', trigger: 'change' }
  ]
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await importCardList({
      Page: currentPage.value,
      PageSize: pageSize.value,
      ...searchForm
    })
    if (res.code === 200) {
      userList.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取卡片列表失败')
    }
  } catch (error) {
    ElMessage.error('获取卡片列表失败')
  } finally {
    loading.value = false
  }
}

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
}

// 文件上传前的验证
const beforeUpload = (file) => {
  if (importForm.fileList.length === 1) {    
    ElMessage.error('只能上传一个文件')
    return false
  }
  const allowedTypes = [
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/csv',
    'application/csv',
    'text/comma-separated-values',
    'text/plain'
  ]
  
  const allowedExtensions = ['.xlsx', '.xls', '.csv']
  const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
  
  const isAllowedType = allowedTypes.includes(file.type) || allowedExtensions.includes(fileExtension)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAllowedType) {
    ElMessage.error('只能上传 Excel 或 CSV 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  
  return true
}

// 文件选择变化
const handleFileChange = (file, fileList) => {
  importForm.file = file.raw
  importForm.fileList = fileList
}

// 文件移除
const handleFileRemove = () => {
  importForm.file = null
  importForm.fileList = []
}

// 导入提交
const handleImportSubmit = async () => {
  if (!importFormRef.value) return
  
  try {
    // 验证表单
    await importFormRef.value.validate()
    
    if (!importForm.file) {
      ElMessage.error('请选择导入文件')
      return
    }
    
    importLoading.value = true
    
    // 创建 FormData
    const formData = new FormData()
    formData.append('File', importForm.file)
    formData.append('MerchantId', importForm.MerchantId)
    formData.append('UpstreamPlatformId', importForm.UpstreamPlatformId)
    
    // 调用导入接口
    const res = await importCard(formData)
    
    if (res.code === 200) {
      ElMessage.success('导入成功')
      // 关闭对话框并重新加载列表
      handleImportClose()
      getList()
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    console.error('导入错误:', error)
    ElMessage.error('导入失败，请检查文件格式或网络连接')
  } finally {
    importLoading.value = false
  }
}

// 关闭导入对话框
const handleImportClose = () => {
  importDialogVisible.value = false
  // 重置导入表单
  if (importFormRef.value) {
    importFormRef.value.resetFields()
  }
  importForm.file = null
  importForm.fileList = []
  importForm.MerchantId = null
  importForm.UpstreamPlatformId = null
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    MerchantId: null,
    UpstreamPlatformId: null,
    CardNumber: '',
    Status: null
  })
  currentPage.value = 1
  getList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getList()
}

// 新增
const handleAdd = () => {
  dialogVisible.value = true
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    const res = await addCard({...userForm})
    if (res.code === 200) {
      ElMessage.success('添加卡片成功')
    } else {
      ElMessage.error(res.message)
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    CardNumber: '',
    MerchantId: null,
    UpstreamPlatformId: null
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

const getUpstreamPlatformOptions = async () => {
  try {
    const res = await upstreamPlatformList()
    if (res.code === 200) {      
      upstreamPlatformOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 生命周期
onMounted(() => {
  getList()
  getMerchantIdOptions()
  getUpstreamPlatformOptions()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.template-download {
  text-align: center;
}

.template-download p {
  margin-bottom: 10px;
  color: #606266;
}

.format-tips {
  font-size: 14px;
  color: #909399 !important;
  margin-bottom: 20px !important;
}

.download-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.template-preview {
  margin-top: 20px;
  text-align: left;
}

.template-preview h4 {
  margin-bottom: 10px;
  color: #303133;
}

.template-note {
  margin-top: 10px;
  font-size: 12px;
  color: #e6a23c;
  background: #fdf6ec;
  padding: 8px;
  border-radius: 4px;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.import-tips h4 {
  margin-bottom: 10px;
  color: #303133;
}

.import-tips p {
  margin-bottom: 5px;
  color: #606266;
  font-size: 14px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

:deep(.el-upload) {
  display: block;
}

:deep(.el-upload__tip) {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>